<template>
  <div class="linkage">
    <div>
      <!-- country -->
      <el-select v-model="item.country"
                 default-first-option
                 filterable
                 value-key="country"
                 style="width:217px"
                 placeholder="请选择国家">
        <el-option label="中国" value="中国"></el-option>
<!--        <el-option v-for="item in countryList" :key="item.name" :label="item.name" :value="item.name"></el-option>-->
      </el-select>

      <!-- province -->
      <el-select v-model="item.province"
                 default-first-option
                 filterable
                 value-key="province"
                 style="width:217px"
                 placeholder="请选择省份">
        <el-option v-for="item in provinceList" :key="item.name" :label="item.name" :value="item.name"></el-option>
      </el-select>

      <!-- city -->
      <el-select v-model="item.city"
                 default-first-option
                 filterable
                 value-key="city"
                 style="width:217px"
                 placeholder="请选择城市">
        <el-option v-for="item in cityList" :key="item.name" :label="item.name" :value="item.name"></el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
export default {
  name: "AddressSelector",
  props: ["item"],
  data() {
    return {
      allProvinceList: require('@/config/province.json'),
      allCityList: require('@/config/city.json'),
      provinceList: [],
      cityList: []
    }
  },
  mounted() {
    this.loadProvinceList()
    this.loadCityList()
  },
  computed: {
    selectCountry() {
      return this.item.country
    },
    selectProvince() {
      return this.item.province
    },
    selectCity() {
      return this.item.city
    }
  },
  watch: {
    selectCountry() {
      this.loadProvinceList()
    },
    selectProvince() {
      this.loadCityList()
    }
  },
  methods: {
    loadProvinceList() {
      if ("中国" === this.selectCountry){
        this.provinceList = this.allProvinceList
      }
    },
    loadCityList() {
      const _this = this;
      if (this.selectProvince) {
        const c = this.provinceList.filter((function (c) {
              return c.name === _this.selectProvince
            }
        ));
        if (c.length) {
          const i = c[0].province;
          this.cityList = this.allCityList.filter((function(e) {
                return e.province === i
              }
          ))
        }
      }
    },
    selectCountryFun(country) {
      if ("中国" !== country){
        this.provinceList = []
        this.cityList = []
      }
      this.item.province = ""
      this.item.city = ""
    },
    selectProvinceFun(province) {
      province || (this.cityList = [])
      this.item.city = ""
    }
  }
}
</script>

<style scoped>
.linkage {
  display: flex
}

.linkage div {
  margin-right: 5px
}
</style>